package cn.itrip.auth.controller;

import cn.itrip.auth.service.TokenService;
import cn.itrip.auth.service.UserService;
import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.beans.vo.ItripTokenVO;
import cn.itrip.beans.vo.userinfo.ItripUserVO;
import cn.itrip.common.DtoUtil;
import cn.itrip.common.EmptyUtils;
import cn.itrip.common.ErrorCode;
import cn.itrip.common.MD5;
import org.hibernate.validator.constraints.Email;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;

/**
 * @author 瑾
 */
@Controller
@RequestMapping("/api")
public class LoginController {
    @Resource(name = "tokenService")
    private TokenService tokenService;

    @Resource(name = "userService")
    private UserService userService;
    @RequestMapping(value = "/dologin",method = RequestMethod.POST,produces = "application/json")
    public    @ResponseBody Dto login(@RequestParam String name, @RequestParam String password, HttpServletRequest request){
        ItripUser itripUser = null;
        try {
            itripUser = this.userService.login(name, MD5.getMd5(password,32));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //判断用户名和密码是否正确
        if(EmptyUtils.isNotEmpty(itripUser)){
           //用户提交过来的HTTP头里面的UserId的参数，标识唯一用户
            String userAgent = "";
            userAgent=request.getHeader("user-agent");
            System.out.println("---保存token时的agent为："+userAgent);
            try {
                //获得一条token信息
                String token = tokenService.generateToken(userAgent,itripUser);

                //将token存储到redisc中
                this.tokenService.saveToken(token,itripUser);

            //返回token信息， 封装到vo里面
                //token字符串  过期时期  生成时间
                ItripTokenVO vo = new ItripTokenVO(token
                        , Calendar.getInstance().getTimeInMillis()+2*60*60*1000
                        , Calendar.getInstance().getTimeInMillis()
                );
                return DtoUtil.returnDataSuccess(vo);
            } catch (Exception e) {
                e.printStackTrace();
                return DtoUtil.returnFail(e.getMessage(),ErrorCode.AUTH_AUTHENTICATION_FAILED);
            }


        }else {
            //用户帐号或密码输入错误
            return DtoUtil.returnFail("用户名或密码错误", ErrorCode.AUTH_AUTHENTICATION_FAILED);
        }



    }




}
